package a.b.mvc6.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

/**
 * 自定义事件监听器
 * TODO 其他事件的监听在这里写
 */
@Component
@Slf4j
public class MyEventListener {

    @EventListener
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 应用程序上下文
        ApplicationContext context = event.getApplicationContext();
        String name = context.getDisplayName();
        // 处理事件
        log.info("应用程序 :{} 上下文已初始化完毕", name);
    }

    @EventListener
    public void stopApplicationEvent(ContextClosedEvent event) {
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        while (drivers.hasMoreElements()) {
            Driver driver = drivers.nextElement();
            try {
                DriverManager.deregisterDriver(driver);
                log.info("JDBC驱动：{} 已卸载！", driver);
            } catch (SQLException e) {
                log.error("应用程序停止时出现问题！", e);
            }
        }

        String name = event.getApplicationContext().getDisplayName();
        log.info("应用程序 :{} 上下文已停止", name);
    }
}
